#coding:utf-8
import logging
from django import template
from datetime import datetime, timedelta
from google.appengine.ext import webapp
from google.appengine.api import users

__all__ = ['register', 'default_filter']

register = template.Library()

def timezone(value, offset):
    return value + timedelta(hours=offset)

def params(generator, params):
    generator.set_params(params)
    return generator

def limitnum(list,num):
    if type(list) ==type([]):
        return list[:num]
    
register.filter(timezone)
register.filter(params)
register.filter(limitnum)

def datetz(date,arg):  #datetime with timedelta
    '格式时间并+8小时'
    t=timedelta(seconds=28800)
    return webapp.template.django.template.defaultfilters.date(date+t, arg)

def commentclass(data):
    '返回0-9'
    return data % 10

def cutwords(data):
    '截取字符串'
    if len(data)<=28:
        return data
    else:
        return data[:28]+'...'

def safeget(options,key):
    a=''
    try:
        a=options.__getattribute__(key)
    except:
        a=''
    return a

def title(name):
    if name.upper() =='POST':
        return "文章"
    elif name.upper() == 'PAGE':
        return "页面"
    else:
        return name

def power(press):
    try:
        object.__getattribute__(users,"level")
    except AttributeError:
        users.level = 0   
    if users.level and users.level >= press:
        return True
    else:
        return False    
    
register.filter(datetz)
register.filter(commentclass)
register.filter(cutwords)
register.filter(safeget)
register.filter(title)
register.filter(power)